<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.name"
          clearable
          placeholder="输入名称搜索"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.type"
          clearable
          size="small"
          placeholder="照片归属"
          class="filter-item"
          style="width: 115px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in dict.photo_type" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
        <el-select
          v-model="query.verifyStatus"
          clearable
          size="small"
          placeholder="审核状态"
          class="filter-item"
          style="width: 115px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in dict.info_verify_status" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
        <el-select
          v-model="query.isEnable"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 100px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in dict.data_status" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="830px"
      >
        <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="80px">
          <el-container>
            <el-main style="padding: 0">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请给照片取个名称" style="width: 540px;" />
              </el-form-item>
              <el-form-item label="拍摄日期" prop="time">
                <el-date-picker v-model="form.time" type="date" placeholder="请选择日期" style="width: 135px;" />
              </el-form-item>
              <el-form-item label="拍摄地点" prop="address">
                <el-input v-model="form.address" placeholder="请输入照片的拍摄地点" style="width: 310px;" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入照片的附加信息" style="width: 540px;" />
              </el-form-item>
            </el-main>
            <el-aside style="width: 160px; padding: 2px; background-color: white;">
              <!--   上传文件   -->
              <el-upload
                ref="upload"
                accept="image/jpeg,image/gif,image/png"
                list-type="picture-card"
                :on-remove="handleRemove"
                :limit="1"
                :class="{ hide: hideUpload }"

                :on-change="handleChange"
                :before-upload="beforeUpload"
                :auto-upload="false"
                :headers="headers"
                :on-success="handleSuccess"
                :on-error="handleError"
                :file-list="fileList"
                :action="imgFileUploadApi + '?name=' + form.name"
              >
                <i class="el-icon-plus" />
                <div slot="tip" class="el-upload__tip" style="margin: 0; padding: 0; line-height: 20px;">请上传大小不超过100M图片</div>
              </el-upload>
            </el-aside>
          </el-container>
          <el-row>
            <el-form-item label="照片归属">
              <el-radio v-for="item in dict.photo_type" :key="item.id" v-model="form.type" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-form-item>
          </el-row>
          <el-row v-if="form.type === '1'">
            <el-form-item label="入学年份">
              <el-select
                v-model="form.enterDate"
                class="filter-item"
                style="width: 130px"
                clearable
                remote
                :remote-method="getYears()"
                @change="loadColleges"
              >
                <el-option v-for="item in years" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="学院">
              <el-select
                v-model="academyDepartId"
                clearable
                filterable
                placeholder="请选择"
                class="input"
                @change="loadMajors"
              >
                <el-option
                  v-for="item in colleges"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="专业">
              <el-select v-model="form.departmentId" clearable filterable placeholder="请选择" class="input">
                <el-option
                  v-for="item in majors"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-row>
          <el-form-item v-permission="permission.verify" label="审核状态">
            <el-select v-model="form.verifyStatus" filterable placeholder="请选择" style="width: 300px;">
              <el-option v-for="item in dict.info_verify_status" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio v-for="item in dict.data_status" :key="item.id" v-model="form.isEnable" :label="item.value">{{ item.label }}</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="upload">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="名称" width="120" />
        <el-table-column prop="type" label="照片归属" width="100">
          <template slot-scope="scope">
            {{ dict.label.photo_type[scope.row.type] }}
          </template>
        </el-table-column>
        <!--        <el-table-column prop="department" label="院系班级" width="160">>
          <template slot-scope="scope">
            <div>{{ scope.row.department == null ? '' : scope.row.department.name }}</div>
          </template>
        </el-table-column> -->
        <el-table-column prop="time" label="拍摄日期" width="110">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.time, '{y}年{m}月{d}日') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="拍摄地点" width="200" />
        <el-table-column prop="path" label="预览图">
          <template slot-scope="scope">
            <el-image
              :src=" baseApi + '/upload/图片/' + scope.row.path"
              :preview-src-list="[baseApi + '/upload/图片/' + scope.row.path]"
              fit="contain"
              lazy
              class="el-avatar"
            >
              <div slot="error">
                <i class="el-icon-document" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="verifyStatus" label="审核状态" width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.verifyStatus=='0'">待审核</div>
            <div v-if="scope.row.verifyStatus=='1'" style="color: limegreen">审核通过</div>
            <div v-if="scope.row.verifyStatus=='2'" style="color: #FF4949">审核未通过</div>
          </template>
        </el-table-column>
        <el-table-column prop="uploadUser" label="上传用户">
          <template slot-scope="scope">
            <div>{{ scope.row.uploadUser == null ? '' : scope.row.uploadUser.username }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="上传时间" width="135">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reviewer" label="审核者">
          <template slot-scope="scope">
            <div>{{ scope.row.reviewer == null ? '' : scope.row.reviewer.username }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="reviewTime" label="审核时间" width="135">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.reviewTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isEnable" label="状态" fixed="right" width="50">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isEnable" active-color="#409EFF" inactive-color="#F56C6C" @change="changeEnabled(scope.row, scope.row.isEnable)" />
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','photos:edit','photos:del']" label="操作" width="150px" align="center" fixed="right">
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import {
  mapGetters
} from 'vuex'
import {
  getToken
} from '@/utils/auth'
import crudPhotos from '@/api/anniversary/photos'
import CRUD, {
  presenter,
  header,
  form,
  crud
} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getColleges, getDepartments, getDepartmentYears } from '@/api/anniversary/department'

const defaultForm = {
  id: null,
  name: null,
  userId: null,
  type: '0',
  departmentId: null,
  time: null,
  address: null,
  path: null,
  verifyStatus: '0',
  sort: 999,
  remark: null,
  isEnable: 'false'
}
export default {
  name: 'Photos',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['photo_type', 'info_verify_status', 'data_status'],
  cruds() {
    return CRUD({
      title: '民大剪影',
      url: 'api/photos',
      sort: 'id,desc',
      crudMethod: { ...crudPhotos
      }
    })
  },
  data() {
    return {
      years: [],
      loading: false,
      colleges: [],
      majors: [],
      academyDepartId: null,
      hideUpload: false,
      limitCount: 1,
      departments: [],
      headers: {
        'Authorization': getToken()
      },
      fileList: [],
      permission: {
        add: ['admin', 'photos:add'],
        edit: ['admin', 'photos:edit'],
        del: ['admin', 'photos:del'],
        verify: ['admin', 'photos:verify']
      },
      rules: {
        name: [{
          required: true,
          message: '名称不能为空',
          trigger: 'blur'
        }],
        time: [{
          required: true,
          message: '拍摄时间不能为空',
          trigger: 'blur'
        }],
        address: [{
          required: true,
          message: '拍摄地点不能为空',
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi',
      'imgFileUploadApi'
    ])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.id == null) {
        form.userId = this.user.id
      }
      this.fileList = []
      if (form.path != null) {
        var url = this.baseApi + '/upload/图片/' + form.path
        this.fileList.push({
          name: form.path,
          url: url
        })
        this.hideUpload = this.fileList.length >= this.limitCount
      } else { this.hideUpload = false }

      if (form.departmentId !== null) {
        form.type = '1'
        this.getSupDepartments(form.departmentId)
      }

      form.verifyStatus = `${form.verifyStatus}`
      form.isEnable = `${form.isEnable}`
    },
    getYears() {
      if (this.loading === false) {
        setTimeout(() => {
          this.loading = true
          getDepartmentYears().then(res => {
            if (res != null) {
              this.years = res
            }
          })
        }, 100)
      }
    },
    upload() {
      if (this.fileList.length === 0) {
        this.crud.notify('请先选择要上传的照片', CRUD.NOTIFICATION_TYPE.ERROR)
      } else {
        // 若未修改图片地址，则只提交表单
        if (this.form.path === this.fileList[0].name) {
          this.crud.submitCU()
        } else {
          // 若修改了图片地址，则上传文件并提交表单
          this.$refs.upload.submit()
        }
      }
    },
    loadColleges(e) {
      this.colleges = []
      this.majors = []
      this.academyDepartId = null
      this.form.departmentId = null
      if (e != null && e !== '') {
        getColleges(e).then(res => {
          this.colleges = res
        })
      }
    },
    loadMajors(e) {
      this.majors = []
      this.form.departmentId = null
      if (e != null && e !== '') {
        var params = { isEnable: true, parentId: e }
        getDepartments(params).then(res => {
          this.majors = res.content
        })
      }
    },
    beforeUpload(file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isIMAGE) {
        this.loading = false
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isIMAGE && isLt2M
    },
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount
    },
    handleSuccess(response, file, fileList) {
      // this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.form.path = response
      // console.log(this.baseApi + "/file/图片/" + response)
      this.$refs.upload.clearFiles()
      this.crud.submitCU()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    handleChange(files, fileList) {
      this.hideUpload = fileList.length >= this.limitCount
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]
      }
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.data_status[val] + '" ' + data.name + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudPhotos.edit(data).then(res => {
          this.crud.notify(this.dict.label.data_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.isEnable = !data.isEnable
        })
      }).catch(() => {
        data.isEnable = !data.isEnable
      })
    }
  }
}
</script>

<style lang="scss" scoped>
	/deep/ .el-image__error,
	.el-image__placeholder {
		background: none;
	}

	/deep/ .el-image-viewer__wrapper {
		top: 55px;
	}

	/deep/ .el-list-enter-active,
	/deep/ .el-list-leave-active {
		transition: none;
	}

	/deep/ .el-list-enter,
	/deep/ .el-list-leave-active {
		opacity: 0;
	}

	.hide /deep/ .el-upload{
        display:none;   /* 上传按钮隐藏 */
    }
</style>
